package com.fileshare.web.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.fileshare.web.constant.DateConstant.*;

/**
 * 日期工具类
 */
public class DateUtil {
    private static final Map<String, SimpleDateFormat> DATE_FORMATTER = new HashMap<>();

    static {
        DATE_FORMATTER.put(YYYY_MM_DD, new SimpleDateFormat(YYYY_MM_DD));
        DATE_FORMATTER.put(YYYY_MM_DD_FLASH, new SimpleDateFormat(YYYY_MM_DD_FLASH));
        DATE_FORMATTER.put(YYYY_MM_DD_DOT, new SimpleDateFormat(YYYY_MM_DD_DOT));
        DATE_FORMATTER.put(YYYY_MM_DD_H24_M_S, new SimpleDateFormat(YYYY_MM_DD_H24_M_S));
        DATE_FORMATTER.put(YYYY_MM_DD_H24_M_S_FLASH, new SimpleDateFormat(YYYY_MM_DD_H24_M_S_FLASH));
        DATE_FORMATTER.put(YYYY_MM_DD_H24_M_S_DOT, new SimpleDateFormat(YYYY_MM_DD_H24_M_S_DOT));
        DATE_FORMATTER.put(M_DD_YYYY_FLASH, new SimpleDateFormat(M_DD_YYYY_FLASH));
        DATE_FORMATTER.put(M_DD_YYYY_DOT, new SimpleDateFormat(M_DD_YYYY_DOT));
        DATE_FORMATTER.put(DD_MMM_YYYY_DOT, new SimpleDateFormat(DD_MMM_YYYY_DOT));
        DATE_FORMATTER.put(DD_MMM_YYYY, new SimpleDateFormat(DD_MMM_YYYY));
    }

    private DateUtil() {
    }

    public static String format(Date date) {
        return format(date, YYYY_MM_DD);
    }

    public static String format(Date date, String pattern) {
        SimpleDateFormat format = DATE_FORMATTER.get(pattern);
        if (Objects.isNull(format)) {
            format = new SimpleDateFormat(pattern);
            DATE_FORMATTER.put(pattern, format);
        }
        return format.format(date);
    }
}
